Skip to main content

React : Implementing Server-Side Pagination in React and .NET Core C#

 

Server-side pagination is essential for managing large datasets efficiently in web applications. In this blog post, we'll explore how to implement server-side pagination using React for the frontend and .NET Core for the backend. By fetching data from the server in chunks, we can improve performance and user experience while handling large datasets.
Step 1: Set Up the .NET Core Web API:
Begin by creating a .NET Core Web API project to serve as the backend for our pagination example. Define endpoints to retrieve paginated data from the server.
Create a .NET Core Web API Project:

dotnet new webapi -n PaginationAPI
cd PaginationAPI
Define a Model:
Create a simple model class to represent the data entity.
// DataModel.cs
public class DataModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    // Add more properties as needed
}
an example of setting up a mock repository in a .NET Core Web API project using Entity Framework Core to connect to a SQL database.
Install Entity Framework Core:
Ensure you have Entity Framework Core installed in your project. You can install it via NuGet Package Manager or .NET CLI.
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools

Set Up DbContext: Create a DbContext class to represent the database context and define a DbSet for your model.

// DataContext.cs
using Microsoft.EntityFrameworkCore;

public class DataContext : DbContext
{
    public DbSet<DataModel> Data { get; set; }

    public DataContext(DbContextOptions<DataContext> options) : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // Configure entity mappings, relationships, etc.
    }
}

Configure Connection String: Update your appsettings.json file to include the connection string for your SQL Server database.

// appsettings.json
{
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Database=YourDatabaseName;User=YourUsername;Password=YourPassword;"
  }
}

Register DbContext in Dependency Injection Container: Configure your DbContext in the ConfigureServices method of the Startup class.

// Startup.cs
using Microsoft.EntityFrameworkCore;

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<DataContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    services.AddScoped<IDataRepository, DataRepository>();
    services.AddControllers();
}

Create Repository Interface: Define an interface for your repository.

// IDataRepository.cs
using System.Collections.Generic;

public interface IDataRepository
{
    IEnumerable<DataModel> GetData();
    // Add more methods as needed
}

Implement Repository Class: Create a repository class that implements the interface and interacts with the DbContext.

// DataRepository.cs
using System.Collections.Generic;
using System.Linq;

public class DataRepository : IDataRepository
{
    private readonly DataContext _context;

    public DataRepository(DataContext context)
    {
        _context = context;
    }

    public IEnumerable<DataModel> GetData()
    {
        return _context.Data.ToList();
    }

    // Implement additional repository methods as needed
}
With these steps, you have set up a mock repository in your .NET Core Web API project using Entity Framework Core to connect to a SQL database. You can now use this repository to interact with your database and perform CRUD operations on your data entities.

Step 2: Implement Server-Side Pagination in .NET Core: Create a controller to handle requests for paginated data.
// DataController.cs
using Microsoft.AspNetCore.Mvc;

[Route("api/[controller]")]
[ApiController]
public class DataController : ControllerBase
{
    private readonly MockRepository _repository;

    public DataController(MockRepository repository)
    {
        _repository = repository;
    }

    [HttpGet]
    public IActionResult GetPaginatedData(int page = 1, int pageSize = 10)
    {
        var data = _repository.GetData();
        var paginatedData = data.Skip((page - 1) * pageSize).Take(pageSize);
        return Ok(paginatedData);
    }
}
Step 3: Set Up React Application: Generate a new React application using Create React App or any other preferred method. This will serve as the frontend for our pagination example.
npx create-react-app pagination-app
cd pagination-app
Step 4: Implement Pagination Component in React: Create a pagination component in React to allow users to navigate through pages and fetch paginated data from the server.
// PaginationComponent.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';

const PaginationComponent = () => {
  const [data, setData] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(0);

  useEffect(() => {
    fetchData();
  }, [currentPage]);

  const fetchData = async () => {
    try {
      const response = await axios.get(`/api/data?page=${currentPage}`);
      setData(response.data);
      // Calculate total pages based on response
      setTotalPages(10); // Example: Assuming 10 total pages
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  };

  const goToPage = (page) => {
    setCurrentPage(page);
  };

  return (
    <div>
      <ul>
        {data.map((item) => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
      <div>
        {Array.from({ length: totalPages }).map((_, index) => (
          <button key={index + 1} onClick={() => goToPage(index + 1)}>{index + 1}</button>
        ))}
      </div>
    </div>
  );
};

export default PaginationComponent;
Step 5: Incorporate Pagination Component into App Component: Integrate the pagination component into your main App component to display paginated data in your React application.
// App.js
import React from 'react';
import PaginationComponent from './PaginationComponent';

const App = () => {
  return (
    <div>
      <h1>Pagination Example</h1>
      <PaginationComponent />
    </div>
  );
};

export default App;
Conclusion: By following the steps outlined in this blog post, you can implement server-side pagination in your React and .NET Core web application. Server-side pagination helps optimize performance and manage large datasets efficiently, providing a seamless user experience. With React handling the frontend and .NET Core powering the backend, you can create robust and scalable web applications capable of handling significant amounts of data.

Comments

Popular posts from this blog

Implementing and Integrating RabbitMQ in .NET Core Application: Shopping Cart and Order API

RabbitMQ is a robust message broker that enables communication between services in a decoupled, reliable manner. In this guide, we’ll implement RabbitMQ in a .NET Core application to connect two microservices: Shopping Cart API (Producer) and Order API (Consumer). 1. Prerequisites Install RabbitMQ locally or on a server. Default Management UI: http://localhost:15672 Default Credentials: guest/guest Install the RabbitMQ.Client package for .NET: dotnet add package RabbitMQ.Client 2. Architecture Overview Shopping Cart API (Producer): Sends a message when a user places an order. RabbitMQ : Acts as the broker to hold the message. Order API (Consumer): Receives the message and processes the order. 3. RabbitMQ Producer: Shopping Cart API Step 1: Install RabbitMQ.Client Ensure the RabbitMQ client library is installed: dotnet add package RabbitMQ.Client Step 2: Create the Producer Service Add a RabbitMQProducer class to send messages. RabbitMQProducer.cs : using RabbitMQ.Client; usin...

How Does My .NET Core Application Build Once and Run Everywhere?

One of the most powerful features of .NET Core is its cross-platform nature. Unlike the traditional .NET Framework, which was limited to Windows, .NET Core allows you to build your application once and run it on Windows , Linux , or macOS . This makes it an excellent choice for modern, scalable, and portable applications. In this blog, we’ll explore how .NET Core achieves this, the underlying architecture, and how you can leverage it to make your applications truly cross-platform. Key Features of .NET Core for Cross-Platform Development Platform Independence : .NET Core Runtime is available for multiple platforms (Windows, Linux, macOS). Applications can run seamlessly without platform-specific adjustments. Build Once, Run Anywhere : Compile your code once and deploy it on any OS with minimal effort. Self-Contained Deployment : .NET Core apps can include the runtime in the deployment package, making them independent of the host system's installed runtime. Standardized Libraries ...

Clean Architecture: What It Is and How It Differs from Microservices

In the tech world, buzzwords like   Clean Architecture   and   Microservices   often dominate discussions about building scalable, maintainable applications. But what exactly is Clean Architecture? How does it compare to Microservices? And most importantly, is it more efficient? Let’s break it all down, from understanding the core principles of Clean Architecture to comparing it with Microservices. By the end of this blog, you’ll know when to use each and why Clean Architecture might just be the silent hero your projects need. What is Clean Architecture? Clean Architecture  is a design paradigm introduced by Robert C. Martin (Uncle Bob) in his book  Clean Architecture: A Craftsman’s Guide to Software Structure and Design . It’s an evolution of layered architecture, focusing on organizing code in a way that makes it  flexible ,  testable , and  easy to maintain . Core Principles of Clean Architecture Dependency Inversion : High-level modules s...